package com.liang.excel.core;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.liang.excel.core.domain.AgentResponseData;
import com.liang.excel.core.domain.BusinessData;
import com.liang.excel.core.domain.LostData;
import com.liang.excel.core.domain.StoreResponseData;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 导演
 *
 * @author liangyehao
 * @date 2021/04/26
 */
public class Director {

    public static String doWork(String filePath, File basicFile, String startTimeStr, String endTimeStr) throws FileNotFoundException {

        long startTime = System.currentTimeMillis();

        List<BusinessData> handledList = handleData(basicFile);

        System.out.println("1.handleData:" + handledList.size());

        DateTime start = DateUtil.parse(startTimeStr);
        DateTime end = DateUtil.parse(endTimeStr);

        List<BusinessData> selectData = selectData(start, end, handledList);



        System.out.println("2.selectData:" + selectData.size());

        List<AgentResponseData> agentResponseData = countByAgent(selectData);

        LostData lostData = new LostData();
        List<StoreResponseData> storeResponseData = countByStore(selectData, lostData);


        //格式化格式
        String format = "YYYYMMddHHmmss";
        // DateTimeFormatter.ofPattern方法根据指定的格式输出时间
        String formatDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern(format));

        String fileName = filePath+startTimeStr+"~"+endTimeStr+"区府商机转化" + formatDateTime + ".xlsx";
        FileOutputStream outputStream = new FileOutputStream(fileName);
        ExcelWriter excelWriter = EasyExcel.write(outputStream).build();

        WriteSheet mainSheet = EasyExcel.writerSheet(0, "处理后明细表").head(BusinessData.class).build();
        excelWriter.write(handledList,mainSheet);

        WriteSheet sheet1 = EasyExcel.writerSheet(1, "门店统计表").head(StoreResponseData.class).build();
        excelWriter.write(storeResponseData,sheet1);

        WriteSheet sheet2 = EasyExcel.writerSheet(2, "经纪人统计表").head(AgentResponseData.class).build();
        excelWriter.write(agentResponseData,sheet2);

        // 丢客五张表
        WriteSheet sheet3 = EasyExcel.writerSheet(3, "已录客未带看").head(BusinessData.class).build();
        excelWriter.write(lostData.getRecordButNotWithList(),sheet3);

        WriteSheet sheet4 = EasyExcel.writerSheet(4, "已录客被他人成交").head(BusinessData.class).build();
        excelWriter.write(lostData.getRecordedButDealByOthersList(),sheet4);

        WriteSheet sheet5 = EasyExcel.writerSheet(5, "未录客被他人录入").head(BusinessData.class).build();
        excelWriter.write(lostData.getUnRecordButRecordByOthersList(),sheet5);

        WriteSheet sheet6 = EasyExcel.writerSheet(6, "未录客被他人带看").head(BusinessData.class).build();
        excelWriter.write(lostData.getUnRecordButWithByOthersList(),sheet6);

        WriteSheet sheet7 = EasyExcel.writerSheet(7, "未录客被他人成交").head(BusinessData.class).build();
        excelWriter.write(lostData.getUnRecordButDealByOthersList(),sheet7);


        excelWriter.finish();

        System.out.println("共处理了: "+handledList.size()+" 条数据,耗时: " + (System.currentTimeMillis() - startTime)/1000 + "s");

        return fileName;
    }


    private static List<StoreResponseData> countByStore(List<BusinessData> selectData, LostData lostData) {
        List<StoreResponseData> storeResponseDataList = new ArrayList<>();
        // 按门店分组
        Map<String, List<BusinessData>> stores = selectData.stream().collect(Collectors.groupingBy(BusinessData::getStores));
        for (Map.Entry<String, List<BusinessData>> entry : stores.entrySet()) {
            StoreResponseData storeResponseData = new StoreResponseData();
            List<BusinessData> totalData = entry.getValue();
            BusinessData businessData = totalData.get(0);
            String store = businessData.getStores();
            storeResponseData.setStore(store);

            storeResponseData.buildStatistics(totalData);
            storeResponseData.buildLost(totalData,lostData);

            storeResponseDataList.add(storeResponseData);
        }
        TotalUtils.total(storeResponseDataList,new StoreResponseData());
        return storeResponseDataList;
    }


    private static List<AgentResponseData> countByAgent(List<BusinessData> selectData) {

        List<AgentResponseData> agentResponseDataList = new ArrayList<>();

        // 按经纪人分组
        Map<String, List<BusinessData>> agents = selectData.stream().collect(Collectors.groupingBy(BusinessData::getAgentName));

        for (Map.Entry<String, List<BusinessData>> entry : agents.entrySet()) {
            AgentResponseData agentResponseData = new AgentResponseData();
            String agentName = entry.getKey();
            List<BusinessData> totalData = entry.getValue();
            BusinessData businessData = totalData.get(0);
            String store = businessData.getStores();
            String agentOffice = businessData.getAgentOffice();
            agentResponseData.setStore(store);
            agentResponseData.setAgentName(agentName);
            agentResponseData.setBrokerageType(agentOffice);

            agentResponseData.buildStatistics(totalData);
            agentResponseData.buildLost(totalData, null);

            agentResponseDataList.add(agentResponseData);

        }

        // 按分店名字排序
        List<AgentResponseData> sortedByStoreName = agentResponseDataList.stream().sorted(Comparator.comparing(AgentResponseData::getStore)).collect(Collectors.toList());
        TotalUtils.total(sortedByStoreName,new AgentResponseData());
        return sortedByStoreName;
    }

    private static List<BusinessData> selectData(DateTime start, DateTime end, List<BusinessData> list) {
        return list.stream().filter(businessData -> {
            Date businessTime = businessData.getBusinessTime();
            DateTime when = DateTime.of(businessTime);
            return when.isAfterOrEquals(start) && when.isBefore(DateUtil.offsetDay(end,1));
        }).collect(Collectors.toList());
    }


    private static List<BusinessData> handleData(File baseFile) {
        // 读取数据


        DemoDataListener dataListener = new DemoDataListener();

        EasyExcel.read(baseFile, BusinessData.class, dataListener).sheet().doRead();

        List<BusinessData> list = dataListener.getList();

        // 处理数据

        ExcelHandler<BusinessData> handler = new DefaultExcelHandler();

        List<BusinessData> handledList = handler.handle(list);

        System.out.println();


        return handledList;
    }


}
